<template>
  <el-row :gutter="20">
    <el-col :span="16">
      <ContentWrap title="申请信息">
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="formRules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="任务名称" prop="taskName">
                <el-input v-model="formData.taskName" placeholder="请输入任务名称" />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="负责人" prop="chargeUserId">
                <UserSelect @node-change="handleChargeUserChange" v-model="formData.chargeUserId" />
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="12">
              <el-form-item label="任务号" prop="taskNumber">
                <el-input v-model="formData.taskNumber" placeholder="请输入任务号" />
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="任务类型" prop="taskType">
                <el-select v-model="formData.taskType" placeholder="请选择任务类型">
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.OA_TASK_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="12">
            <el-form-item label="收费金额" prop="paymentAmount" >
              <el-input v-model="formData.paymentAmount" type="number"  placeholder="请输入金额" />
            </el-form-item>
          </el-col>
          
          <el-row>
            <el-col :span="24">
              <el-form-item label="沟通信息" prop="remark">
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入沟通信息,明确任务内容和要求"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
                <OaFileManager :folderDisabled="true" @file-select-success="fileSelectSuccess" />
            </el-col>
          </el-row>
          <div class="mt-5" style="text-align: center;">  
            <el-button :disabled="formLoading" type="primary" class="w80px" @click="debouncedHandleSubmit">
              提 交
            </el-button>
          </div>
        </el-form>
      </ContentWrap>
    </el-col>

    <!-- 审批相关：流程信息 -->
    <el-col :span="8">
      <ContentWrap title="审批流程" :bodyStyle="{ padding: '0 20px 0' }">
        <ProcessInstanceTimeline
          ref="timelineRef"
          :activity-nodes="activityNodes"
          :show-status-icon="false"
          @select-user-confirm="selectUserConfirm"
        />
      </ContentWrap>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { MainTasksApi, MainTasksVO } from '@/api/oa/maintasks'
import { useTagsViewStore } from '@/store/modules/tagsView'
import UserSelect from '@/views/system/user/UserSelect.vue'
import UserSelectMultiple from '@/views/system/user/UserSelectMultiple.vue'
import FileDialog from '@/views/infra/file/FileDialog.vue'
import * as FileApi from '@/api/infra/file'

// 审批相关：import
import * as DefinitionApi from '@/api/bpm/definition'
import ProcessInstanceTimeline from '@/views/bpm/processInstance/detail/ProcessInstanceTimeline.vue'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { CandidateStrategy, NodeId } from '@/components/SimpleProcessDesignerV2/src/consts'
import { ApprovalNodeInfo } from '@/api/bpm/processInstance'
import { useDebounceFn } from '@vueuse/core'

defineOptions({ name: 'OaMainTasksCreate' })

const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<MainTasksVO>({
  taskNumber: '',
  taskName: '',
  taskType: undefined,
  chargeUserId: undefined,
  chargeUserName: '',
  teamMembers: [], // 初始化为空数组
  teamMemberNames: '',
  companyInfo: '',
  taskContent: '',
  startTime: undefined,
  endTime: undefined,
  isPaymentReceived: undefined,
  paymentMethod: undefined,
  attachments: [],
  paymentReceived: undefined,
  paymentAmount: undefined,
  paymentDate: undefined,
  remark: undefined
})
const formRules = reactive({
  // chargeUserId: [{ required: true, message: '负责人不能为空', trigger: 'change' }],
  // taskNumber: [{ required: true, message: '任务号不能为空', trigger: 'blur' }],
  taskName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  taskType: [{ required: true, message: '任务类型不能为空', trigger: 'change' }],
  paymentAmount: [{ required: true, message: '请输入收费金额', trigger: 'blur' }],
  teamMembers: [{ required: true, message: '参与人员不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

// 审批相关：变量
const processDefineKey = 'oa_main_tasks' // 流程定义 Key
const startUserSelectTasks = ref([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref({}) // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref({}) // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const activityNodes = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([]) // 审批节点信息
const processDefinitionId = ref('')

const selectedFileIds = ref<string[]>([])
const selectedFileDetails = ref<{ id: string, title: string }[]>([])
const fileDialogRef = ref()

/** 提交表单 */
const handleSubmit = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  try {
    // 将参与人员数组转换为逗号分隔的字符串
    const submitData = {
      ...formData.value,
      teamMembers: Array.isArray(formData.value.teamMembers) 
        ? formData.value.teamMembers.join(',')
        : formData.value.teamMembers,
      // 处理文件信息，使用selectedFileIds中的文件ID
      files: selectedFileIds.value.join(',')
    }
    await MainTasksApi.createMainTasks(submitData)
    message.success('发起成功')
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'MainTasksOwner' })
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 使用防抖包装提交函数，防止重复提交
const debouncedHandleSubmit = useDebounceFn(handleSubmit, 500)

const fileSelectSuccess = (fileIds: string[]) => {
  console.log(fileIds)
  selectedFileIds.value = fileIds
  formData.value.files = fileIds.join(',')
}

/** 审批相关：获取审批详情 */
const getApprovalDetail = async () => {
  try {
    const data = await ProcessInstanceApi.getApprovalDetail({
      processDefinitionId: processDefinitionId.value,
      // TODO 小北：可以支持 processDefinitionKey 查询
      activityId: NodeId.START_USER_NODE_ID,
      processVariablesStr: JSON.stringify({ day: daysDifference() }) // 解决 GET 无法传递对象的问题，后端 String 再转 JSON
    })

    if (!data) {
      message.error('查询不到审批详情信息！')
      return
    }
    // 获取审批节点，显示 Timeline 的数据
    activityNodes.value = data.activityNodes

    // 获取发起人自选的任务
    startUserSelectTasks.value = data.activityNodes?.filter(
      (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
    )
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        if (
          tempStartUserSelectAssignees.value[node.id] &&
          tempStartUserSelectAssignees.value[node.id].length > 0
        ) {
          startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id]
        } else {
          startUserSelectAssignees.value[node.id] = []
        }
      }
    }
  } finally {
  }
}

/** 审批相关：选择发起人 */
const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

// 计算天数差
// TODO @小北：可以搞到 formatTime 里面去，然后看看 dayjs 里面有没有现成的方法，或者辅助计算的方法。
const daysDifference = () => {
  const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
  const diffTime = Math.abs(Number(formData.value.endTime) - Number(formData.value.startTime))
  return Math.floor(diffTime / oneDay)
}

/** 负责人被点击事件 */
const handleChargeUserChange = (user: any) => {
  formData.value.chargeUserId = user.id
  formData.value.chargeUserName = user.nickname
}

/** 参与人员被点击事件 */
const handleTeamMembersChange = (users: any[]) => {
  formData.value.teamMemberNames = users.map(user => user.nickname).join(',')
}

/** 初始化 */
onMounted(async () => {
  // TODO @小北：这里可以简化，统一通过 getApprovalDetail 处理么？
  const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
    undefined,
    processDefineKey
  )

  if (!processDefinitionDetail) {
    message.error('主任务管理的流程模型未配置，请检查！')
    return
  }
  processDefinitionId.value = processDefinitionDetail.id
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks

  // 审批相关：加载最新的审批详情，主要用于节点预测
  await getApprovalDetail()
})

/** 审批相关：预测流程节点会因为输入的参数值而产生新的预测结果值，所以需重新预测一次, formData.value可改成实际业务中的特定字段 */
watch(
  formData.value,
  (newValue, oldValue) => {
    if (!oldValue) {
      return
    }
    if (newValue && Object.keys(newValue).length > 0) {
      // 记录之前的节点审批人
      tempStartUserSelectAssignees.value = startUserSelectAssignees.value
      startUserSelectAssignees.value = {}
      // 加载最新的审批详情,主要用于节点预测
      getApprovalDetail()
    }
  },
  {
    immediate: true
  }
)

const openFileDialog = () => {
  fileDialogRef.value.open()
}

// 获取文件详情
const getFileListByIds = async (ids: string[]) => {
  return FileApi.getFileListByIds(ids)
}

watch(selectedFileIds, async (newVal) => {
  if (!newVal || newVal.length === 0) {
    selectedFileDetails.value = []
    return
  }
  selectedFileDetails.value = await getFileListByIds(newVal)
}, { immediate: true })

// 文件上传成功的回调
const handleUploadSuccess = (response: any, file: any) => {
  // 将上传成功的文件信息添加到 attachments 数组
  formData.value.attachments = formData.value.attachments || []
  formData.value.attachments.push({
    id: response.data.id, // 保存文件ID
    name: file.name,
    url: response.data.url,
    size: file.size
  })
}

// 文件删除的回调
const handleRemove = (file: any) => {
  const index = formData.value.attachments?.findIndex(item => item.name === file.name)
  if (index !== undefined && index > -1) {
    formData.value.attachments?.splice(index, 1)
  }
}
</script>
